/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.column.modular.column.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.barn.modular.barn.entity.BizBarn;
import vip.xiaonuo.barn.modular.barn.mapper.BizBarnMapper;
import vip.xiaonuo.column.modular.column.entity.BizColumn;
import vip.xiaonuo.column.modular.column.entity.ColumnTreeNode;
import vip.xiaonuo.column.modular.column.entity.ColumnView;
import vip.xiaonuo.column.modular.column.mapper.BizColumnMapper;
import vip.xiaonuo.column.modular.column.mapper.BizColumnTreeNodeMapper;
import vip.xiaonuo.column.modular.column.mapper.ColumnViewMapper;
import vip.xiaonuo.column.modular.column.param.BizColumnAddParam;
import vip.xiaonuo.column.modular.column.param.BizColumnEditParam;
import vip.xiaonuo.column.modular.column.param.BizColumnIdParam;
import vip.xiaonuo.column.modular.column.param.BizColumnPageParam;
import vip.xiaonuo.column.modular.column.service.BizColumnService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.henhouse.modular.henhouse.mapper.BizHenhouseMapper;
import vip.xiaonuo.henhouse.modular.henhouse.service.impl.util.TreeNode;

import javax.annotation.Resource;
import java.util.*;

/**
 * 栏区Service接口实现类
 *
 * @author zyb
 * @date  2023/11/20 19:56
 **/
@Service
public class BizColumnServiceImpl extends ServiceImpl<BizColumnMapper, BizColumn> implements BizColumnService {

    @Resource
    private BizBarnMapper barnMapper;

    @Resource
    private BizHenhouseMapper henhouseMapper;

    @Resource
    private BizColumnTreeNodeMapper columnTreeNodeMapper;

    @Resource
    private ColumnViewMapper columnViewMapper;

    @Override
    public Page<ColumnView> page(BizColumnPageParam bizColumnPageParam) {
        QueryWrapper<ColumnView> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizColumnPageParam.getSign())) {
            queryWrapper.lambda().like(ColumnView::getSign, bizColumnPageParam.getSign());
        }
        if(ObjectUtil.isNotEmpty(bizColumnPageParam.getTypeId())) {
            queryWrapper.lambda().like(ColumnView::getTypeId, bizColumnPageParam.getTypeId());
        }
        if(ObjectUtil.isNotEmpty(bizColumnPageParam.getBarnId())) {
            queryWrapper.lambda().like(ColumnView::getBarnId, bizColumnPageParam.getBarnId());
        }
        if(ObjectUtil.isNotEmpty(bizColumnPageParam.getState())) {
            queryWrapper.lambda().eq(ColumnView::getState, bizColumnPageParam.getState());
        }
        if(ObjectUtil.isAllNotEmpty(bizColumnPageParam.getSortField(), bizColumnPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizColumnPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizColumnPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizColumnPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ColumnView::getId);
        }
        return columnViewMapper.selectPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizColumnAddParam bizColumnAddParam) {
        BizColumn bizColumn = BeanUtil.toBean(bizColumnAddParam, BizColumn.class);
        String barnId = bizColumnAddParam.getBarnId();
        BizBarn barn = barnMapper.selectById(barnId);
        if(ObjectUtil.isEmpty(barn)) {
            throw new CommonException("该栏舍不存在！");
        }
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().substring(0,4);
        bizColumn.setName(barn.getName() + "_" + bizColumn.getTypeId() + uuidStr);
        bizColumn.setRemainingCapacity(bizColumnAddParam.getCapacity());
        this.save(bizColumn);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizColumnEditParam bizColumnEditParam) {
        BizColumn bizColumn = this.queryEntity(bizColumnEditParam.getId());
        BeanUtil.copyProperties(bizColumnEditParam, bizColumn);
        this.updateById(bizColumn);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizColumnIdParam> bizColumnIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizColumnIdParamList, BizColumnIdParam::getId));
    }

    @Override
    public BizColumn detail(BizColumnIdParam bizColumnIdParam) {
        return this.queryEntity(bizColumnIdParam.getId());
    }

    @Override
    public BizColumn queryEntity(String id) {
        BizColumn bizColumn = this.getById(id);
        if(ObjectUtil.isEmpty(bizColumn)) {
            throw new CommonException("栏区不存在，id值为：{}", id);
        }
        return bizColumn;
    }

    @Override
    public List<BizColumn> getListByBarnId(String barnId) {
        if (barnId.isEmpty()){
            throw new CommonException("栏舍不存在，id值为：{}", barnId);
        }
        LambdaQueryWrapper<BizColumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizColumn::getBarnId,barnId);
        return this.list(queryWrapper);
    }
    @Override
    public List<TreeNode> getTree() {
        List<TreeNode> treeData = new ArrayList<>();
        Map<String,TreeNode> henhouseMap = new HashMap<>();
        Map<String,TreeNode> barnMap = new HashMap<>();

        List<ColumnTreeNode> columnTreeNodes = columnTreeNodeMapper.selectList(null);
        // 遍历栏区节点
        for (ColumnTreeNode columnTreeNode : columnTreeNodes) {
            TreeNode treeNode = new TreeNode();
            if (columnTreeNode.getHenhouseId() != null) {
                // 获取鸡舍节点
                TreeNode henhouseNode = henhouseMap.get(columnTreeNode.getHenhouseId());
                // 如果没获取到则创建一个鸡舍节点并存入map中,存入结果集中
                if (henhouseNode == null) {
                    // 因为前端展示的是名，而需要传回来的是id，所以lable是名
                    henhouseNode = new TreeNode(columnTreeNode.getHenhouseName(),columnTreeNode.getHenhouseId());
                    henhouseMap.put(columnTreeNode.getHenhouseId(), henhouseNode);
                    treeData.add(henhouseNode);
                }

                // 将栏舍节点挂载到鸡舍节点下
                if (columnTreeNode.getBarnId()!= null){
                    // 同鸡舍节点创建过程类似
                    TreeNode barnNode = barnMap.get(columnTreeNode.getBarnId());
                    if (barnNode == null) {
                        barnNode = new TreeNode(columnTreeNode.getBarnName(),columnTreeNode.getBarnId());
                        barnMap.put(columnTreeNode.getBarnId(), barnNode);
                        henhouseNode.getChildren().add(barnNode);
                    }

                    // 将栏区节点挂载到栏舍节点下
                    TreeNode columnNode = new TreeNode(columnTreeNode.getName(), columnTreeNode.getId());
                    barnNode.getChildren().add(columnNode);
                }
            }
        }

        return treeData;
    }

    @Override
    public String getCategoryById(String id) {
        LambdaQueryWrapper<BizColumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(BizColumn::getSign).eq(BizColumn::getId, id);
        BizColumn column = this.getOne(queryWrapper);
        return column.getSign();
    }
}
